package com.qiguliuxing.dts.db.service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.qiguliuxing.dts.db.dao.DtsCouponMapper;
import com.qiguliuxing.dts.db.dao.DtsCouponUserMapper;
import com.qiguliuxing.dts.db.domain.DtsCoupon;
import com.qiguliuxing.dts.db.domain.DtsCouponUser;
import com.qiguliuxing.dts.db.util.CouponConstant;

@Service
public class DtsCouponService {
	@Resource
	private DtsCouponMapper couponMapper;
	@Resource
	private DtsCouponUserMapper couponUserMapper;

	/**
	 * 查询，空参数
	 *
	 * @param offset
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	public List<DtsCoupon> queryList(int offset, int limit, String sort, String order) {
		QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();
		return queryList(queryWrapper, offset, limit, sort, order);
	}

	/**
	 * 查询
	 *
	 * @param criteria
	 *            可扩展的条件
	 * @param offset
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	public List<DtsCoupon> queryList(QueryWrapper<DtsCoupon> queryWrapper, int offset, int limit, String sort,
			String order) {
		queryWrapper.eq("type", CouponConstant.TYPE_COMMON);
		queryWrapper.eq("status", CouponConstant.STATUS_NORMAL);
		queryWrapper.eq("deleted", false);
		queryWrapper.orderByDesc(sort);
		IPage<DtsCoupon> iPage = new Page<>(offset, limit);
		return couponMapper.selectPage(iPage, queryWrapper).getRecords();
	}

	public int queryTotal() {
		QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", CouponConstant.TYPE_COMMON);
		queryWrapper.eq("status", CouponConstant.STATUS_NORMAL);
		queryWrapper.eq("deleted", false);
		return couponMapper.selectCount(queryWrapper).intValue();
	}

	public List<DtsCoupon> queryAvailableList(Integer userId, int offset, int limit) {
		assert userId != null;
		// 过滤掉登录账号已经领取过的coupon
		QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();
		QueryWrapper<DtsCouponUser> userQueryWrapper = new QueryWrapper<>();
		userQueryWrapper.lambda().eq(DtsCouponUser::getUserId, userId);
		List<DtsCouponUser> used = couponUserMapper.selectList(userQueryWrapper);
		if (used != null && !used.isEmpty()) {
			queryWrapper.notIn("id", used.stream().map(DtsCouponUser::getCouponId).collect(Collectors.toList()));
		}
		return queryList(queryWrapper, offset, limit, "add_time", "desc");
	}

	public List<DtsCoupon> queryList(int offset, int limit) {
		return queryList(offset, limit, "add_time", "desc");
	}

	public DtsCoupon findById(Integer id) {
		return couponMapper.selectById(id);
	}

	public DtsCoupon findByCode(String code) {
		QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("code", code);
		queryWrapper.eq("type", CouponConstant.TYPE_CODE);
		queryWrapper.eq("status", CouponConstant.STATUS_NORMAL);
		queryWrapper.eq("deleted", false);
		List<DtsCoupon> couponList = couponMapper.selectList(queryWrapper);
		if (couponList.size() > 1) {
			throw new RuntimeException("");
		} else if (couponList.size() == 0) {
			return null;
		} else {
			return couponList.get(0);
		}
	}

	/**
	 * 查询新用户注册优惠券
	 *
	 * @return
	 */
	public List<DtsCoupon> queryRegister() {
		QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", CouponConstant.TYPE_REGISTER);
		queryWrapper.eq("status", CouponConstant.STATUS_NORMAL);
		queryWrapper.eq("deleted", false);
		return couponMapper.selectList(queryWrapper);
	}

	public List<DtsCoupon> querySelective(String name, Short type, Short status, Integer page, Integer limit,
			String sort, String order) {
		QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(name)) {
			queryWrapper.like("name", name);
		}
		if (type != null) {
			queryWrapper.eq("type", CouponConstant.TYPE_COMMON);
		}
		if (status != null) {
			queryWrapper.eq("status", CouponConstant.STATUS_NORMAL);
		}
		queryWrapper.eq("deleted", false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}

		IPage<DtsCoupon> iPage = new Page<>(page, limit);
		return couponMapper.selectPage(iPage, queryWrapper).getRecords();
	}

	public void add(DtsCoupon coupon) {
		coupon.setAddTime(LocalDateTime.now());
		coupon.setUpdateTime(LocalDateTime.now());
		couponMapper.insert(coupon);
	}

	public int updateById(DtsCoupon coupon) {
		coupon.setUpdateTime(LocalDateTime.now());
		return couponMapper.updateById(coupon);
	}

	public void deleteById(Integer id) {
		couponMapper.deleteById(id);
	}

	private String getRandomNum(Integer num) {
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		base += "0123456789";

		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < num; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 生成优惠码
	 *
	 * @return 可使用优惠码
	 */
	public String generateCode() {
		String code = getRandomNum(8);
		while (findByCode(code) != null) {
			code = getRandomNum(8);
		}
		return code;
	}

	/**
	 * 查询过期的优惠券: 注意：如果timeType=0, 即基于领取时间有效期的优惠券，则优惠券不会过期
	 *
	 * @return
	 */
	public List<DtsCoupon> queryExpired() {
		QueryWrapper<DtsCoupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsCoupon::getTimeType, CouponConstant.TIME_TYPE_TIME);
		queryWrapper.eq("status", CouponConstant.STATUS_NORMAL);
		queryWrapper.lambda().eq(DtsCoupon::getEndTime, LocalDate.now());
		queryWrapper.eq("deleted", false);
		return couponMapper.selectList(queryWrapper);
	}
}
